package cn.lh.pet.controller;

import cn.lh.pet.service.IPetService;
import cn.lh.pet.domain.Pet;
import cn.lh.pet.query.PetQuery;
import cn.lh.basic.util.JsonResult;
import cn.lh.basic.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
* 后端接口类；
*/
@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    public IPetService petService;

    /**
     * 接口：添加或修改
     * @param pet  传递的实体
     * @return JsonResult 响应给前端
     */
    @PutMapping
    public JsonResult addOrUpdate(@RequestBody Pet pet){
        try {
            if( pet.getId()!=null)
                petService.update(pet);
            else
                petService.add(pet);
            return JsonResult.set(true,"操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.set(false,"操作失败");
        }
    }

    /**
    * 接口：删除
    * @param id
    * @return JsonResult 响应给前端
    */
    @DeleteMapping(value="/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        try {
            petService.del(id);
            return JsonResult.set(true,"批量删除成功");
        } catch (Exception e) {
        e.printStackTrace();
            return JsonResult.set(false,"删除失败");
        }
    }

    /**
    * 接口：批量删除
    * @param ids
    * @return JsonResult 响应给前端
    */
    @PatchMapping
    public JsonResult patchDelete(@RequestBody Long[] ids){
        try {
                petService.batchDelete(ids);
            return JsonResult.set(true,"批量删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.set(false,"批量删除失败");
        }
    }

    /**
    * 接口：查询单个对象
    * @param id
    */
    @GetMapping("/{id}")
    public Pet findOne(@PathVariable("id")Long id) {
        return petService.findById(id);
    }


    /**
    * 接口：查询所有
    * @return
    */
    @GetMapping
    public List<Pet> findAll(){
        return petService.findAll();
    }


   /**
    * 接口：分页查询或高级查询
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping
    public Page<Pet> queryPage(@RequestBody PetQuery query) {
        return petService.queryPage(query);
    }

    @PostMapping("/onsale")
    public JsonResult onsale(@RequestBody Long[] ids){
        try {
            petService.onSale(ids);
            return JsonResult.set(true, "上架成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.set(false, "系统错误稍后重试");
        }
    }
    @PostMapping("/offsale")
    public JsonResult offsale(@RequestBody Long[] ids){
        try {
            petService.offSale(ids);
            return JsonResult.set(true, "下架成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.set(false, "系统错误稍后重试");
        }
    }
}
